javascript array rand [2]

javascript array rand [2]
Already did a straight function to get a random element from an array. It’s even easier as a prototype to extend the base Array object. Then you can just call the “random” method on any array.
<script type="text/javascript">//<![CDATA[
Array.prototype.random = function () {
  return this[ Math.floor( Math.random() * this.length ) ];
}
var stuff = new Array('ant', 'grasshopper', 'scorpion', 'frog');
for ( i = 0 ; i < 10; i++ ) { document.write( stuff.random() + ' '); } //]]> </script>
You can also shuffle/randomize your whole array up front with the Fisher-‌Yates algorithm and here are other ways to extend the native Array class.
[close] Permanent link · http://querylog.com/q/javascript+array+rand+[2]

Suggested HTML for linking:
Link preview: javascript array rand [2]
04 October 2006 · Internet & computing
The page found by the original query:
Randomize arrays in JavaScript with the Fi…
Browse by the page—15 Q&R each
« previous | more »